package org.example.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.example.model.Code;
import org.example.service.CodeService;
import org.example.service.CodeService2;
import org.example.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private CodeService codeService;

    @Autowired
    private CodeService2 codeService2;

    @Reference
    EmailService emailService;

    @GetMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email, HttpServletResponse response){
        System.out.println("create email="+email);
        if(StringUtils.isEmpty(email)){
            return false;
        }
        Code c = new Code();
        c.setEmail(email);
        // check last code generation time
        List<Code> prev = codeService.findByEmailOrderByCreatetimeDesc(c);
        if(prev!=null && prev.size()>0){
            Code res = prev.get(0);
            Timestamp now = new Timestamp(System.currentTimeMillis());
            if(now.getTime()-res.getCreatetime().getTime()<60*1000){
                // last code within 1 min, return 403
                response.setStatus(403);
                return false;
            }
        }
        // random number 10000<x<1000000
        String code = Integer.toString((int)((Math.random()*9+1)*100000));
        c.setCode(code);
        c.setCreatetime(new Timestamp(System.currentTimeMillis()));
        // 10 min timeout
        c.setExpiretime(new Timestamp(System.currentTimeMillis()+10*60*1000L));
        codeService.addCode(c);
        System.out.println("code generated:"+code);
        return emailService.email(email,code);
    }

    @GetMapping("/validate/{email}/{code}") //0-correct/1-wrong/2-timeout
    public int validateEmail(@PathVariable("email") String email,
                                 @PathVariable("code") String code){
        return codeService2.validateEmail(email,code);
    }
}
